// src/utils/getLocation.js
export function getUserLocation() {
    return new Promise((resolve, reject) => {
      // 检查浏览器是否支持 Geolocation API
      if (!navigator.geolocation) {
        reject(new Error('Geolocation is not supported by this browser.'));
        return;
      }
  
      // 获取用户当前位置
      navigator.geolocation.getCurrentPosition(
        (position) => {
          const { latitude, longitude } = position.coords;
        //   console.log('获取到的经纬度:', { latitude, longitude });
  
          const apiKey = '627e0fdeb087eaabaabd692deae24adc'; // 替换为你的高德地图 API Key
          const url = `https://restapi.amap.com/v3/geocode/regeo?key=${apiKey}&location=${longitude},${latitude}`;
  
          // 发起请求到高德地图逆地理编码接口
          fetch(url)
            .then((response) => {
              if (!response.ok) {
                throw new Error('Network response was not ok.');
              }
              return response.json();
            })
            .then((data) => {
            //   console.log('高德地图返回的数据:', data); // 打印高德地图返回的数据
              if (data.status === '1' && data.info === 'OK') {
                const addressComponent = data.regeocode.addressComponent;
                const province = addressComponent.province;
                const city = addressComponent.city || addressComponent.township; // 如果没有城市信息，使用镇区信息
                resolve({ province, city });
              } else {
                reject(new Error(`Failed to get location information: ${data.info}`));
              }
            })
            .catch((error) => {
              reject(error);
            });
        },
        (error) => {
          reject(error);
        }
      );
    });
  }